package com.woniuxy.carlife.carlifecomprehensiveweb.util;

import com.woniuxy.carlife.carlifecomprehensiveweb.config.MinioConfig;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;
import io.minio.errors.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @ClassName: MinioTemplate
 * @ Description:（封装文件上传类）
 * @author: yanzhongliang     
 * @date: Update in 14:43 2021/4/8
 */

public class MinioTemplate {

    @Resource
    private MinioConfig mc;

    private MinioClient client;

    public MinioTemplate(MinioConfig mc){
        this.mc=mc;
        this.client=MinioClient.builder()
                .endpoint(mc.getEndpoint())
                .credentials(mc.getAccessKey(),mc.getSecretKey()).build();
    }

//    更改图片名字并上传方法
    public String uploadFile(String fileName, String bucketName, InputStream stream,Long size,String contentType){
        PutObjectArgs poa= PutObjectArgs.builder()
                .object(fileName).bucket(bucketName).stream(stream,size,mc.getPartSize())
                .contentType(contentType)
                .build();
        try {
            client.putObject(poa);
            return mc.getEndpoint()+"/"+bucketName+fileName;
        } catch (ErrorResponseException|InsufficientDataException|InternalException
                |InvalidKeyException|InvalidResponseException|NoSuchAlgorithmException|
                ServerException|XmlParserException|IOException e) {
            e.printStackTrace();
            throw new RuntimeException("上传失败");
        }

    }

//    删除图片方法
    public boolean deleteFile(String fileName,String bucketName){
        try {
            RemoveObjectArgs roa= RemoveObjectArgs.builder().bucket(bucketName).object(fileName).build();
            client.removeObject(roa);
            return true;
        } catch (ErrorResponseException|InsufficientDataException|InternalException
                |InvalidKeyException|InvalidResponseException|NoSuchAlgorithmException|
                ServerException|XmlParserException|IOException e) {
            e.printStackTrace();
            throw new RuntimeException("删除失败");
        }
    }
}
